<template>
  <!-- <x-skeleton :type="skeleton.type" :loading="skeleton.loading" :config="skeleton.config"> -->

  <view class="bg-gray-100 min-h-[100vh]" :style="themeColor()">
    <view class="w-[100%] h-[340rpx]" :style="headerStyle">
    </view>


    <mescroll-body ref="mescrollRef" bottom="60px" @init="mescrollInit" :down="{ use: false }" @up="getAllAppListFn">
      <view v-if="goodsList.length" :class="['sidebar-margin']">
        <view v-for="(item, index) in goodsList" :key="index"
          class="bg-white flex px-[20rpx] py-[24rpx] rounded-[var(--rounded-small)] overflow-hidden top-mar"
          :class="{ 'mb-[20rpx]': (index + 1) == goodsList.length }" @click="toDetail(item.spuId)">
          <image v-if="item.picUrl" class="w-[190rpx] h-[190rpx] rounded-[var(--rounded-mid)]" :src="img(item.picUrl)"
            :mode="'aspectFill'" @error="item.picUrl = 'static/resource/images/diy/shop_default.jpg'">
          </image>
          <image v-else class="w-[190rpx] h-[190rpx] rounded-[var(--rounded-mid)]"
            :src="img('static/resource/images/diy/shop_default.jpg')" :mode="'aspectFill'"></image>
          <view class="flex-1 flex flex-col ml-[20rpx] py-[6rpx]">
            <view class="text-[28rpx] text-[#333] leading-[40rpx] multi-hidden mb-[10rpx]">
              <view class="brand-tag" v-if="item.brandName">
                {{ item.brandName }}
              </view>
              {{ item.titleName || item.spuName }}
            </view>
            <view v-if="item.goods_label_name && item.goods_label_name.length" class="flex flex-wrap">
              <template v-for="(tagItem, tagIndex) in item.goods_label_name">
                <image class="img-tag" v-if="tagItem.style_type == 'icon' && tagItem.icon" :src="img(tagItem.icon)"
                  mode="heightFix" @error="diyGoods.error(tagItem, 'icon')"></image>
                <view class="base-tag" v-else-if="tagItem.style_type == 'diy' || !tagItem.icon"
                  :style="diyGoods.baseTagStyle(tagItem)">
                  {{ tagItem.label_name }}
                </view>
              </template>
            </view>
            <view class="mt-auto flex justify-between items-baseline">
              <view class="flex items-baseline mt-[20rpx]">
                <view class="text-[var(--price-text-color)] price-font flex items-baseline">
                  <text class="text-[24rpx] font-500 mr-[4rpx]">￥</text>
                  <text class="text-[40rpx] font-500">{{ diyGoods.goodsPrice(item).toFixed(2).split('.')[0]
                  }}</text>
                  <text class="text-[24rpx] font-500">.{{ diyGoods.goodsPrice(item).toFixed(2).split('.')[1]
                  }}</text>
                </view>

              </view>
              <view
                class="text-[24rpx] box-border border-[2rpx] border-solid border-[var(--price-text-color)] px-[16rpx] h-[54rpx] flex-center rounded-[50rpx] text-[var(--price-text-color)]">
                <text class="nc-iconfont nc-icon-fenxiangV6xx-1 mr-[6rpx] !text-[26rpx]"></text>
                <text>赚</text>
                <text class="max-w-[129rpx] truncate" v-if="item.brokerageMinPrice === item.brokerageMaxPrice">{{
                  fen2yuan(item.brokerageMinPrice
                  ) }}元</text>
                <text class="max-w-[129rpx] truncate" v-else>{{ fen2yuan(item.brokerageMinPrice) }} ~
                  {{ fen2yuan(item.brokerageMaxPrice) }}元</text>
              </view>
            </view>
          </view>
        </view>

      </view>
      <mescroll-empty v-if="!goodsList.length && loading" :option="{ tip: '暂无商品', btnText: '去逛逛' }"
        @emptyclick="redirect({ url: '/addon/shop/pages/index', mode: 'reLaunch' })"></mescroll-empty>
    </mescroll-body>

    <tabbar />
  </view>
  <!-- </x-skeleton> -->

</template>

<script setup lang="ts">
import { reactive, ref, onMounted, computed } from 'vue'
import { t } from '@/locale'
import { redirect, img, getToken } from '@/utils/common';
import { getGoodsCategoryTree, getGoodsPages, getSettlementProduct } from '@/addon/shop/api/goods';
import MescrollBody from '@/components/mescroll/mescroll-body/mescroll-body.vue';
import MescrollEmpty from '@/components/mescroll/mescroll-empty/mescroll-empty.vue';
import useMescroll from '@/components/mescroll/hooks/useMescroll.js';
import { onLoad, onPageScroll, onReachBottom } from '@dcloudio/uni-app';
import { useGoods } from '@/addon/shop/hooks/useGoods'
import { getProductBrokeragePrice } from './../api/commission'
const diyGoods = useGoods();

import { fen2yuan, formattingCategory } from '@/utils/formatting';
const { mescrollInit, downCallback, getMescroll } = useMescroll(onPageScroll, onReachBottom);
const skeleton = reactive({
  type: 'list',
  loading: true,
  config: {
    gridRows: 5,
  }
})

const categoryList = ref<Array<Object>>([]);
const goodsList = ref<Array<any>>([]);
// const coupon_id = ref<number | string>('');
const currGoodsCategory = ref<number | string>('');
const mescrollRef = ref(null);
const loading = ref<boolean>(false);
// 标签
const goods_name = ref("");

//列表类型
onLoad(async (option: any) => {
  currGoodsCategory.value = option.curr_goods_category || ''
  goods_name.value = option.goods_name ? decodeURIComponent(option.goods_name) : ''
  // coupon_id.value = option.coupon_id || ''
  await getGoodsCategoryTree().then((res: any) => {
    const initData = { category_name: "全部", category_id: '' };
    categoryList.value.push(initData);

    categoryList.value = categoryList.value.concat(formattingCategory(res.data));
  });
  skeleton.loading = false
})

interface mescrollStructure {
  num: number,
  size: number,
  endSuccess: Function,
  [propName: string]: any
}

const headerStyle = computed(() => {
  return {
    backgroundImage: 'url(' + img('https://files.meton.vip/39bd97e85f3708f181d3cec026ed8516a68432948b7c877fdc849bd15f12cd4c.png') + ') ',
    backgroundSize: 'cover',
    backgroundRepeat: 'no-repeat',
    backgroundPosition: 'bottom',
    // paddingTop:Object.keys(menuButtonInfo).length?(Number(menuButtonInfo.height) * 2 + menuButtonInfo.top * 2 + 77)+'rpx':'77rpx',
  }
})

const getAllAppListFn = (mescroll: mescrollStructure) => {


  loading.value = false;
  let data: object = {
    pageNo: mescroll.num,
    pageSize: mescroll.size,
    subCommissionEnable: true, //分销开关
  };
  getGoodsPages(data).then(async (res: any) => {
    // let newArr = (res.data.data as Array<Object>);
    let newArr = (res.data.list as Array<Object>);
    // 使用 Promise.all 来等待所有佣金请求完成
    await Promise.all(
      newArr.map(async (item: any) => {
        try {
          const res = await getProductBrokeragePrice({ spuId: item.spuId });
          item.brokerageMinPrice = res.data.brokerageMinPrice;
          item.brokerageMaxPrice = res.data.brokerageMaxPrice;
        } catch (error) {
          console.error(`获取商品【${item.name}】的佣金时出错：`, error);
        }
      }),
    );

    //设置列表数据
    if (Number(mescroll.num) === 1) {
      goodsList.value = []; //如果是第一页需手动制空列表
    }
    goodsList.value = goodsList.value.concat(newArr);
    mescroll.endSuccess(newArr.length);
    loading.value = false;
  }).catch(() => {
    loading.value = false;
    mescroll.endErr(); // 请求失败, 结束加载
  })
}




const toDetail = (id: string | number) => {
  redirect({ url: '/addon/shop/pages/goods/detail', param: { goods_id: id }, mode: 'navigateTo' })
}
onMounted(() => {
  setTimeout(() => {
    getMescroll().optUp.textNoMore = t("end");
  }, 500)
});
</script>

<style lang="scss" scoped>
@import '@/addon/shop/styles/common.scss';

.scroll-view-wrap {
  word-break: keep-all;
}

.text-color {
  color: var(--primary-color);
}

.label-select {
  color: var(--primary-color);
  border-color: var(--primary-color);
  background-color: var(--primary-color-light);
}

:deep(.u-popup .u-transition) {
  top: 156rpx !important;
}

.product-warp {
  z-index: 99999;
}

:deep(.tab-bar-placeholder) {
  display: none !important;
}

:deep(.u-tabbar__placeholder) {
  display: none !important;
}

:deep(.u-input__content__clear) {
  width: 28rpx;
  height: 28rpx;
  font-size: 28rpx;
  background-color: var(--text-color-light9);
}

.biserial-goods-list {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;
}
</style>